<!-- subpkg_consult/room/index.vue -->
<script lang="ts" setup>
	import { nextTick, ref } from 'vue'
	import { useUserStore } from '../../stores/user'
	import { io, type Socket } from 'socket.io-client'
	import { orderDetailApi, uploadImgApi } from '@/apis/consult'
	import { OrderDetail } from '../../types/consult'
	import type { MsgData, MsgItem } from '@/types/room.d.ts'
	//组件
	import roomStatusVue from './components/room-status.vue'
	import patientInfoVue from './components/patient-info.vue'
	import notifyInfoVue from './components/notify-info.vue'
	import messageInfoVue from './components/message-info.vue'
	import prescriptionInfoVue from './components/prescription-info.vue'

	const props = defineProps<{ orderId: string; payResult: string; type: string }>()
	//仓库
	const store = useUserStore()
	//1.处理支付失败的情况
	if (props.payResult === 'false') {
		//跳转到我的页面
		uni.switchTab({
			url: '/pages/my/index',
		})
	}

	//2.建立WebSocket连接
	const socket: Socket = io('https://consult-api.itheima.net', {
		auth: { token: 'Bearer ' + store.token },
		query: { orderId: props.orderId },
		transports: ['websocket', 'polling'],
		timeout: 5000,
	})

	socket.on('connect', () => {
		// 建立连接成功
		console.log('连接建立成功')
	})

	socket.on('error', (event) => {
		// 错误异常消息
		console.log('出现错误')
	})

	socket.on('disconnect', () => {
		// 已经断开连接
		console.log('断开连接')
	})

	//监听订单状态的改变
	socket.on('statusChange', () => {
		// console.log('订单状态发生改变~')
		getOrderInfo()
	})
	//获取消息列表
	const msgList = ref([] as MsgItem)
	socket.on('chatMsgList', (msg: MsgData) => {
		msg.data?.forEach((item) => {
			msgList.value.push(
				{ msgType: 31, msg: { content: item.createTime }, id: item.createTime },
				...item.items!
			)
		})
		// console.log(msgList.value)
	})
	//接收医生传过来的消息
	socket.on('receiveChatMsg', (message: MsgItem) => {
		// 修改消息为已读
		socket.emit('updateMsgStatus', message.id)
		// 接收到的消息追加到消息列表中
		msgList.value.push(message)
		// console.log(message)
		nextTick(() => {
			sp.value = `item${msgList.value.length - 1}`
		})
	})

	//给医生发送文字信息
	//输入信息
	const iptMessage = ref('')
	const sendMsg = () => {
		if (iptMessage.value.trim() === '') return
		socket.emit('sendChatMsg', {
			from: store.userId,
			to: orderDetail.value.docInfo.id,
			msgType: 1,
			msg: {
				content: iptMessage.value,
			},
		})
		// console.log(iptMessage.value)
		iptMessage.value = ''
	}

	//发送图片信息
	const sendImages = async () => {
		if (orderDetail.value.status >= 4) return
		//选图片
		const res = await uni.chooseImage()
		// console.log('1', res)
		const path = res.tempFilePaths[0]
		//传图片
		const upLoadRes = await uploadImgApi(path)
		//发送图片
		socket.emit('sendChatMsg', {
			from: store.userId,
			to: orderDetail.value.docInfo.id,
			msgType: 4,
			msg: {
				picture: upLoadRes,
			},
		})
	}

	//订单的详情
	const orderDetail = ref({} as OrderDetail)
	//获取订单详情
	const getOrderInfo = async () => {
		const res = await orderDetailApi(props.orderId)
		orderDetail.value = res
		// console.log(res)
	}
	getOrderInfo()
	//元素滚动到指定的位置
	const sp = ref('')
</script>

<template>
	<view class="room-page">
		<roomStatusVue
			:status="orderDetail.status"
			:statusValue="orderDetail.statusValue"
			:countdown="orderDetail.countdown"
		></roomStatusVue>
		<scroll-view
			refresher-enabled
			refresher-background="#f2f2f2"
			scroll-y
			style="flex: 1; overflow: hidden"
			:scroll-into-view="sp"
		>
			<view class="message-container">
				<!-- 此处将来填充更多代码... -->
				<view v-for="(item, i) in msgList" :id="'item' + i"
					><patientInfoVue
						v-if="item.msgType === 21"
						:info="item.msg.consultRecord"
					></patientInfoVue>

					<notifyInfoVue
						v-if="item.msgType === 31 || item.msgType === 32"
						:type="item.msgType"
						>{{ item.msg.content }}
					</notifyInfoVue>
					<messageInfoVue
						v-if="item.msgType <= 4"
						:type="item.msgType"
						:msgItem="item"
					></messageInfoVue>
					<prescriptionInfoVue
						v-if="item.msgType === 22"
						:preInfo="item.msg.prescription"
					></prescriptionInfoVue>
				</view>
			</view>
		</scroll-view>

		<!-- 发送消息 -->
		<view class="message-bar">
			<template v-if="true">
				<uni-easyinput
					v-model="iptMessage"
					@confirm="sendMsg"
					:disabled="orderDetail.status === 4"
					:clearable="false"
					:input-border="false"
					placeholder-style="font-size: 32rpx; color: #c3c3c5;"
					placeholder="问医生"
				/>
				<view @tap="sendImages" class="image-button">
					<uni-icons size="40" color="#979797" type="image"></uni-icons>
				</view>
			</template>
			<button v-else class="uni-button">咨询其它医生</button>
		</view>
	</view>
</template>

<style lang="scss">
	@import './index.scss';
</style>
